import { fabric } from 'fabric'
import { ref } from 'vue'

export function useCropping(getCanvas) {
  const isCropping = ref(false)
  let cropRect = null

  // 开始裁剪
  const startCropping = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    isCropping.value = true

    // 获取选中的图片对象
    const activeObject = fabricCanvas.getActiveObject()
    if (!activeObject || activeObject.type !== 'image') return

    // 创建裁剪框
    cropRect = new fabric.Rect({
      left: activeObject.left,
      top: activeObject.top,
      width: activeObject.width * activeObject.scaleX,
      height: activeObject.height * activeObject.scaleY,
      fill: 'rgba(0,0,0,0.3)',
      stroke: '#fff',
      strokeWidth: 2,
      strokeDashArray: [5, 5]
    })

    fabricCanvas.add(cropRect)
    fabricCanvas.setActiveObject(cropRect)
    fabricCanvas.renderAll()
  }

  // 应用裁剪
  const applyCrop = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas || !cropRect) return

    // 获取选中的图片对象
    const activeObject = fabricCanvas.getActiveObjects().find(obj => obj.type === 'image')
    if (!activeObject) return

    // 计算裁剪区域
    const cropX = (cropRect.left - activeObject.left) / activeObject.scaleX
    const cropY = (cropRect.top - activeObject.top) / activeObject.scaleY
    const cropWidth = cropRect.width / activeObject.scaleX
    const cropHeight = cropRect.height / activeObject.scaleY

    // 创建临时画布进行裁剪
    const tempCanvas = document.createElement('canvas')
    const tempContext = tempCanvas.getContext('2d')
    tempCanvas.width = cropWidth
    tempCanvas.height = cropHeight

    // 绘制裁剪后的图片
    tempContext.drawImage(
      activeObject._element,
      cropX,
      cropY,
      cropWidth,
      cropHeight,
      0,
      0,
      cropWidth,
      cropHeight
    )

    // 创建新的图片对象
    fabric.Image.fromURL(tempCanvas.toDataURL(), (img) => {
      img.set({
        left: cropRect.left,
        top: cropRect.top,
        scaleX: 1,
        scaleY: 1
      })

      // 移除原图和裁剪框，添加新图
      fabricCanvas.remove(activeObject)
      fabricCanvas.remove(cropRect)
      fabricCanvas.add(img)
      fabricCanvas.setActiveObject(img)
      fabricCanvas.renderAll()

      // 重置裁剪状态
      cropRect = null
      isCropping.value = false
    })
  }

  // 取消裁剪
  const cancelCrop = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas || !cropRect) return

    fabricCanvas.remove(cropRect)
    fabricCanvas.renderAll()

    cropRect = null
    isCropping.value = false
  }

  return {
    isCropping,
    startCropping,
    applyCrop,
    cancelCrop
  }
} 